package com.xinghou.platform.util.apns;

import javapns.Push;
import javapns.communication.exceptions.CommunicationException;
import javapns.communication.exceptions.KeystoreException;
import javapns.notification.PushedNotification;
import javapns.notification.PushedNotifications;

import org.slf4j.Logger;

import com.xinghou.platform.util.log.LoggerFactory;

public class IPhonePush {
	
	private static Logger loggerInfo = LoggerFactory.getServerInfoLogger(IPhonePush.class);
	private static Logger loggerError = LoggerFactory.getServerInfoLogger(IPhonePush.class);

	public static boolean pushMessage(String userId, String token, String message, int badge){
		try {
			PushedNotifications notifications = Push.combined(message,badge, PushConfig.getPushSound(),PushConfig.getCertFile(), 
					PushConfig.getCertPassword(), true, token.replaceAll(" ", ""));
			if(!notifications.isEmpty()){			
				PushedNotification notification = notifications.get(0);
				if (notification.isSuccessful()) {
					loggerInfo.info(new StringBuffer("").append("Iphone Push: userId=").append(userId)
					.append(" token=").append(token).append(" message=").append(message).toString());
					return true;
				} else { 
					Exception e = notification.getException();
					loggerError.error("token="+notification.getDevice().getToken()+" Exception:", e);
				}
			}
		} catch (CommunicationException e) {
			loggerError.error("CommunicationException:", e);
		} catch (KeystoreException e) {
			loggerError.error("KeystoreException:", e);
		}
		return false;
	}
}